package com.zjuh.qss.common.http;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

import wint.lang.utils.CollectionUtil;
import wint.lang.utils.IoUtil;
import wint.lang.utils.MapUtil;
import wint.lang.utils.StringUtil;

public class JDKClientConnector implements ClientConnector {

	private String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko/20100101 Firefox/11.0";
	
	private String accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
	
	private int timeout = 5000;
	
	@Override
	public ClientResponse request(String url, boolean usePost, byte[] postData, String referer, String cookies, String contentType)  throws IOException {
		URL u = new URL(url);
		ClientResponse clientResponse = new ClientResponse();
		HttpURLConnection conn = (HttpURLConnection)u.openConnection();
		conn.setConnectTimeout(timeout);
		conn.setReadTimeout(timeout);
		conn.addRequestProperty("User-Agent", userAgent);
		conn.addRequestProperty("Accept", accept);
		if (!StringUtil.isEmpty(referer)) {
			conn.addRequestProperty("Referer", referer);
		}
		if (cookies != null) {
			conn.addRequestProperty("Cookie", cookies);
		}
		if (usePost) {
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setAllowUserInteraction(false);
			if (contentType != null) {
				conn.addRequestProperty("Content-Type", contentType);
			} else {
				conn.setRequestProperty("Content-type","application/x-www-form-urlencoded");
			}
			if (postData != null) {
				OutputStream os = conn.getOutputStream();
				os.write(postData);
				os.close();
			}
		}
		clientResponse.setHeaders(conn.getHeaderFields());
		InputStream is = conn.getInputStream();
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		IoUtil.copyAndClose(is, bos);
		clientResponse.setData(bos.toByteArray());
		return clientResponse;
	}

	public static String getCharset(Map<String, List<String>> rawHeaders) {
		Map<String, List<String>> lowerCaseHeaders = MapUtil.newHashMap();
		for (Map.Entry<String, List<String>> entry : rawHeaders.entrySet()) {
			String name = entry.getKey();
			if (StringUtil.isEmpty(name)) {
				continue;
			}
			List<String> value = entry.getValue();
			lowerCaseHeaders.put(name.toLowerCase(), value);
		}
		List<String> contentTypes = lowerCaseHeaders.get("content-type");
		if (CollectionUtil.isEmpty(contentTypes)) {
			return null;
		}
		String contentType = contentTypes.get(0);
		String[] parts = contentType.split(";");
		for (String part : parts) {
			if (StringUtil.isEmpty(part)) {
				continue;
			}
			String lowercasePart = part.toLowerCase();
			if (lowercasePart.contains("charset") && lowercasePart.contains("=")) {
				String ret = StringUtil.getFirstAfter(lowercasePart, "=");
				ret = StringUtil.trimToEmpty(ret);
				return ret;
			}
		}
		return null;
	}
	
}
